import React from 'react'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import {
  UsersIcon,
  CubeIcon,
  ChartBarIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  CheckCircleIcon,
  EyeIcon,
  ShieldCheckIcon,
  DocumentTextIcon
} from '@heroicons/react/24/outline'
import { selectUser } from '@/store/slices/authSlice'
import { Card, Button, Badge } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

export const AdminDashboard: React.FC = () => {
  const user = useSelector(selectUser)

  // Mock data - in real app, fetch from API
  const stats = {
    totalUsers: 1247,
    totalPlugins: 89,
    pendingReviews: 12,
    activeUsers: 342,
    newUsersToday: 23,
    newPluginsToday: 5,
    systemHealth: 'healthy' as const
  }

  const recentActivities = [
    {
      id: 1,
      type: 'plugin_submitted',
      message: 'New plugin "Data Visualizer" submitted for review',
      user: 'john.doe',
      timestamp: new Date(Date.now() - 1000 * 60 * 30), // 30 minutes ago
      status: 'pending'
    },
    {
      id: 2,
      type: 'user_registered',
      message: 'New user registered: jane.smith',
      user: 'jane.smith',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2), // 2 hours ago
      status: 'success'
    },
    {
      id: 3,
      type: 'plugin_approved',
      message: 'Plugin "Code Formatter" approved',
      user: 'admin',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4), // 4 hours ago
      status: 'success'
    },
    {
      id: 4,
      type: 'security_alert',
      message: 'Suspicious login attempt detected',
      user: 'system',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 6), // 6 hours ago
      status: 'warning'
    }
  ]

  const pendingReviews = [
    {
      id: 1,
      name: 'Data Visualizer',
      developer: 'john.doe',
      submittedAt: new Date(Date.now() - 1000 * 60 * 60 * 2),
      category: 'development'
    },
    {
      id: 2,
      name: 'Task Manager Pro',
      developer: 'alice.dev',
      submittedAt: new Date(Date.now() - 1000 * 60 * 60 * 8),
      category: 'productivity'
    },
    {
      id: 3,
      name: 'Security Scanner',
      developer: 'security.expert',
      submittedAt: new Date(Date.now() - 1000 * 60 * 60 * 12),
      category: 'security'
    }
  ]

  const quickActions = [
    {
      name: 'Review Plugins',
      description: 'Review pending plugin submissions',
      href: '/admin/plugins/pending',
      icon: CubeIcon,
      color: 'bg-blue-500',
      count: stats.pendingReviews
    },
    {
      name: 'User Management',
      description: 'Manage user accounts and permissions',
      href: '/admin/users',
      icon: UsersIcon,
      color: 'bg-green-500'
    },
    {
      name: 'System Analytics',
      description: 'View system performance and usage',
      href: '/admin/analytics',
      icon: ChartBarIcon,
      color: 'bg-purple-500'
    },
    {
      name: 'Audit Logs',
      description: 'Review system audit logs',
      href: '/admin/audit-logs',
      icon: DocumentTextIcon,
      color: 'bg-orange-500'
    }
  ]

  return (
    <ErrorBoundary>
      <div className="space-y-6">
        {/* Welcome Header */}
        <div className="bg-gradient-to-r from-indigo-600 to-purple-600 rounded-lg p-6 text-white">
          <div className="flex items-center space-x-3 mb-2">
            <ShieldCheckIcon className="h-8 w-8" />
            <h1 className="text-2xl font-bold">Admin Dashboard</h1>
          </div>
          <p className="text-indigo-100">
            Welcome back, {user?.displayName || user?.username}! Monitor and manage the platform.
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <UsersIcon className="h-8 w-8 text-blue-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">Total Users</p>
                <p className="text-2xl font-bold text-gray-900">{stats.totalUsers.toLocaleString()}</p>
                <p className="text-sm text-green-600">+{stats.newUsersToday} today</p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <CubeIcon className="h-8 w-8 text-green-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">Total Plugins</p>
                <p className="text-2xl font-bold text-gray-900">{stats.totalPlugins}</p>
                <p className="text-sm text-green-600">+{stats.newPluginsToday} today</p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ClockIcon className="h-8 w-8 text-yellow-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">Pending Reviews</p>
                <p className="text-2xl font-bold text-gray-900">{stats.pendingReviews}</p>
                <p className="text-sm text-yellow-600">Needs attention</p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ChartBarIcon className="h-8 w-8 text-purple-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">Active Users</p>
                <p className="text-2xl font-bold text-gray-900">{stats.activeUsers}</p>
                <p className="text-sm text-purple-600">Last 24h</p>
              </div>
            </div>
          </Card>
        </div>

        {/* Main Content Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Quick Actions */}
          <div className="lg:col-span-1">
            <Card className="p-6">
              <Card.Header>
                <Card.Title>Quick Actions</Card.Title>
                <Card.Description>
                  Common administrative tasks
                </Card.Description>
              </Card.Header>
              <Card.Content>
                <div className="space-y-4">
                  {quickActions.map((action) => (
                    <Link
                      key={action.name}
                      to={action.href}
                      className="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <div className={`flex-shrink-0 p-2 rounded-lg ${action.color}`}>
                        <action.icon className="h-6 w-6 text-white" />
                      </div>
                      <div className="ml-4 flex-1">
                        <div className="flex items-center justify-between">
                          <p className="text-sm font-medium text-gray-900">{action.name}</p>
                          {action.count && (
                            <Badge variant="danger" size="sm">{action.count}</Badge>
                          )}
                        </div>
                        <p className="text-sm text-gray-500">{action.description}</p>
                      </div>
                    </Link>
                  ))}
                </div>
              </Card.Content>
            </Card>
          </div>

          {/* Recent Activity */}
          <div className="lg:col-span-2">
            <Card className="p-6">
              <Card.Header>
                <Card.Title>Recent Activity</Card.Title>
                <Card.Description>
                  Latest system events and user actions
                </Card.Description>
              </Card.Header>
              <Card.Content>
                <div className="space-y-4">
                  {recentActivities.map((activity) => (
                    <div key={activity.id} className="flex items-start space-x-3">
                      <div className="flex-shrink-0">
                        {activity.status === 'success' && (
                          <CheckCircleIcon className="h-5 w-5 text-green-500" />
                        )}
                        {activity.status === 'warning' && (
                          <ExclamationTriangleIcon className="h-5 w-5 text-yellow-500" />
                        )}
                        {activity.status === 'pending' && (
                          <ClockIcon className="h-5 w-5 text-blue-500" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm text-gray-900">{activity.message}</p>
                        <div className="flex items-center space-x-2 mt-1">
                          <p className="text-xs text-gray-500">by {activity.user}</p>
                          <span className="text-xs text-gray-400">•</span>
                          <p className="text-xs text-gray-500">
                            {activity.timestamp.toLocaleTimeString()}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-6 pt-4 border-t border-gray-200">
                  <Button as={Link} to="/admin/audit-logs" variant="outline" size="sm" fullWidth>
                    View All Activity
                  </Button>
                </div>
              </Card.Content>
            </Card>
          </div>
        </div>

        {/* Pending Reviews */}
        {pendingReviews.length > 0 && (
          <Card className="p-6">
            <Card.Header>
              <Card.Title>Pending Plugin Reviews</Card.Title>
              <Card.Description>
                Plugins waiting for approval
              </Card.Description>
            </Card.Header>
            <Card.Content>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Plugin
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Developer
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Category
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Submitted
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {pendingReviews.map((plugin) => (
                      <tr key={plugin.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm font-medium text-gray-900">{plugin.name}</div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">{plugin.developer}</div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <Badge variant="gray" size="sm" className="capitalize">
                            {plugin.category}
                          </Badge>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {plugin.submittedAt.toLocaleDateString()}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                          <div className="flex space-x-2">
                            <Button
                              as={Link}
                              to={`/admin/plugins/${plugin.id}/review`}
                              size="sm"
                              variant="outline"
                              icon={<EyeIcon />}
                            >
                              Review
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div className="mt-6 pt-4 border-t border-gray-200">
                <Button as={Link} to="/admin/plugins/pending" variant="outline" fullWidth>
                  View All Pending Reviews
                </Button>
              </div>
            </Card.Content>
          </Card>
        )}

        {/* System Health Alert */}
        {stats.systemHealth !== 'healthy' && (
          <Card className="p-6 border-red-200 bg-red-50">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="h-6 w-6 text-red-600" />
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">
                  System Health Warning
                </h3>
                <p className="text-sm text-red-700">
                  Some system components require attention. Check the system status page for details.
                </p>
              </div>
              <div className="ml-auto">
                <Button as={Link} to="/admin/system-status" variant="outline" size="sm">
                  Check Status
                </Button>
              </div>
            </div>
          </Card>
        )}
      </div>
    </ErrorBoundary>
  )
}
